package com.tanx.security;

import com.tanx.entity.AccountPrivilege;
import com.tanx.entity.UserAccount;
import com.tanx.service.UserAccountService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;

/**
 * Created by 唐旭 on 2015/7/8.
 */
@Component
public class UserAuthorizingRealm extends AuthorizingRealm {

    @Resource(name = "userAccountService")
    private UserAccountService userAccountService;

    //获取权限
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String username = (String) principals.fromRealm(getName()).iterator().next();
        if (!StringUtils.isEmpty(username)) {
            UserAccount userAccount = userAccountService.getUserAccountByUserName(username);
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            for (AccountPrivilege accountPrivilege : userAccount.getPrivilegeList()) {
                info.addRole(accountPrivilege.getRoleAsString());
                info.addStringPermission(accountPrivilege.getPermissionAsString());
            }
            return info;
        }
        return null;
    }

    //认证用户名密码
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
        String username = token.getUsername();
        String password = String.valueOf(token.getPassword());
        if (!StringUtils.isEmpty(username)) {
            UserAccount userAccount = userAccountService.login(username, password);
            if (userAccount == null) {
                return null;
            }
            //TODO:这里密码暂时存为 明文密码,方便调试
            if (userAccount.getPassword().equals(password)) {
                setSession(userAccount);
                return new SimpleAuthenticationInfo(username, password, getName());
            }
        }
        return null;
    }

    private void setSession(UserAccount userAccount) {
        SecurityUtils.getSubject().getSession().setAttribute("user", userAccount);
    }
}
